#include "file_check.h"
#include <string>
#include "utility.h"

CFileCheck::CFileCheck(){
	
}

CFileCheck::~CFileCheck(){
	
}

void CFileCheck::initialize(){
	
}

void CFileCheck::run(){
	m_TempNode.openFileHelper(m_Dir,"SV");
	m_FileSystem.Open(m_File);
	m_MainNode = m_MainNode.openFileHelper(m_Dir, "SV");
	int j = m_MainNode.nChildNode();
	for(int i = 0; i < j; ++i){
		m_ChildNode = m_MainNode.getChildNode(i);
		this->dir_check((char *)(m_ChildNode.getText()));
	}

	m_MainNode = m_MainNode.openFileHelper(m_File, "SV");
	j = m_MainNode.nChildNode();
	for(int i = 0; i < j; ++i){
		m_ChildNode = m_MainNode.getChildNode(i);
		this->file_check((char *)(m_ChildNode.getText()), (char *)(m_ChildNode.getAttribute("size")), (char *)(m_ChildNode.getAttribute("time")));

	}
}

void CFileCheck::dir_check(char * n_Path){
	_finddata_t finddata;
	std::string FolderPath;
	FolderPath += n_Path;
	FolderPath += "\\*.*";

	long hfile=_findfirst((char *)(FolderPath.c_str()),&finddata);
	if(hfile == -1){
		return;
	}
	if(::GetFileAttributes(finddata.name)&FILE_ATTRIBUTE_DIRECTORY){
		if(finddata.name[0] != '.'){
			FolderPath = "";
			FolderPath += n_Path;
			FolderPath += "\\";
			FolderPath += finddata.name;
			dir_check((char *)(FolderPath.c_str()));			
		}
		return;
	}
	FolderPath = "";
	FolderPath += n_Path;
	FolderPath += "\\";
	FolderPath += finddata.name;
	std::string size = UlToStr(finddata.size);
	char * time =  new char[8];
	_i64toa(finddata.time_write, time, 10);
	if(!m_FileSystem.IsPathExist(FolderPath)){
		XMLNode childNode = m_TempNode.addChild("File");
		childNode.addText(finddata.name);
		childNode.addAttribute("size", (char *)(size.c_str()));
		childNode.addAttribute("time", time);
	}
}

void CFileCheck::file_check(char * n_FileName, char * n_FileSize, char * n_FileWriteTime){
	_finddata_t finddata;
	long hfile=_findfirst(n_FileName,&finddata);
	std::string size = UlToStr(finddata.size);
	char * time =  new char[8];
	_i64toa(finddata.time_write, time, 10);
	if(!(strcmp(n_FileSize, (char *)(size.c_str()))||strcmp(time, n_FileWriteTime))){
		return;
	}

	XMLNode childNode =  m_TempNode.addChild("File");
	childNode.addText(n_FileName);
	childNode.addAttribute("size", n_FileSize);
	childNode.addAttribute("time", n_FileWriteTime);
}